﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewBag.Title = "发货通知单";
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>发货通知单修改</title>
    <!-- 引用Layui的CSS -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 整体表单容器样式 */
        .order-form-container {
            padding: 10px;
        }
        /* 表单行样式 */
        .layui-inline {
            display: flex;
            flex-direction: row;
        }
        /* 操作按钮容器样式 */
        .operation-buttons {
            text-align: right;
            margin-bottom: 10px;
        }
        /* 表格样式 */
        .layui-table {
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="order-form-container">
        <!-- 操作按钮 -->
        <div class="operation-buttons">
            <button class="layui-btn" id="saveButton">保存</button>
            @* <button class="layui-btn layui-btn-primary" id="cancelButton">取消</button> *@
            @*  <button class="layui-btn layui-btn-normal" id="approveButton">审核</button>
            <button class="layui-btn layui-btn-disabled" id="reapproveButton">反审核</button> *@
            @* <button class="layui-btn layui-btn-mini" id="collapseButton">收起</button> *@
        </div>
        <!-- 表单信息 -->
        <div class="layui-inline">
            <label class="layui-input-inline">单据编码:</label>
            <input type="text" id="documentCode" class="layui-input-inline" disabled>&nbsp; &nbsp;
            <label class="layui-input-inline">业务类型:</label>
            <div class="layui-input-inline">
                <select id="businessTypeId">
                    <option value="1">普通发货</option>
                    <option value="2">直运发货</option>
                    <!-- 可根据实际业务添加更多选项 -->
                </select>
            </div>&nbsp; &nbsp;
            <label class="layui-input-inline">仓库:</label>
            <div class="layui-input-inline">
                <select id="warehouseId">
                    <option value="1">成品库</option>
                    <!-- 可根据实际业务添加更多选项 -->
                </select>
            </div>&nbsp; &nbsp;
            <label class="layui-input-inline">收货人:</label>
            <input type="text" id="consignee" class="layui-input-inline">&nbsp; &nbsp;
            <label class="layui-input-inline">运费:</label>
            <input type="text" id="freightCost" class="layui-input-inline">&nbsp; &nbsp;
        </div><br />
        <div class="layui-inline">
            <label class="layui-input-inline">单据日期:</label>
            <input type="date" id="documentDate" value="2025-03-29" class="layui-input-inline">&nbsp; &nbsp;
            <label class="layui-input-inline">操作员:</label>
            <input type="text" id="operator" class="layui-input-inline">&nbsp; &nbsp;
            <label class="layui-input-inline">客户名称:</label>
            <select id="customerName">
                <option value="李迅">李迅</option>
                <option value="张丽">张丽</option>
                <option value="刘慧敏">刘慧敏</option>
                <option value="张经纬">张经纬</option>
                <option value="蒙牛">蒙牛</option>
                <option value="可乐">可乐</option>
                <option value="加多宝">加多宝</option>
                <!-- 可根据实际业务添加更多选项 -->
            </select>
            <button class="layui-input-inline" id="selectCustomerButton">选择</button>&nbsp; &nbsp;
            <label class="layui-input-inline">电话:</label>
            <input type="text" id="phone" class="layui-input-inline">&nbsp; &nbsp;
            <label class="layui-input-inline">装卸费:</label>
            <input type="text" id="handlingFee" class="layui-input-inline">&nbsp; &nbsp;
        </div><br />
        <div class="layui-inline">
            <label class="layui-input-inline">单据状态:</label>
            <input type="text" id="documentStatus" value="开立" class="layui-input-inline" disabled>&nbsp; &nbsp;
            <label class="layui-input-inline">审核员:</label>
            <input type="text" id="auditor" class="layui-input-inline">&nbsp; &nbsp;
            <label class="layui-input-inline">地址:</label>
            <input type="text" id="address" class="layui-input-inline">&nbsp; &nbsp;
        </div><br />
        <div class="layui-inline">
            <label class="layui-input-inline">业务状态:</label>
            <div class="layui-input-inline">
                <select id="businessStatusId">
                    <option value="1">正常</option>
                    <!-- 可根据实际业务添加更多选项 -->
                </select>
            </div>&nbsp; &nbsp;
            <label class="layui-input-inline">审核日期:</label>
            <input type="date" id="auditDate" class="layui-input-inline">&nbsp; &nbsp;
            <label class="layui-input-inline">交付日期:</label>
            <input type="date" id="deliveryDate" class="layui-input-inline">&nbsp; &nbsp;
        </div><br />
        <div class="layui-inline">
            <label class="form-label" class="layui-input-inline">备注信息:</label>
            <input type="text" id="remark" class="layui-input-inline">&nbsp; &nbsp;
        </div><br />

        <!-- 表单信息表格操作按钮 -->
        <div class="form-row">
            @* <button class="layui-btn layui-btn-xs" id="importButton">引入</button> *@
            <button class="layui-btn layui-btn-xs" id="addMaterialButton">新增物料</button>
        </div>
        <!-- 表单信息表格 -->
        <table class="layui-table" id="materialTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>销售订单号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>型号规格</th>
                    <th>主计量</th>
                    <th>数量</th>
                    <th>件数</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['layer', 'form', 'jquery'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;
            // 获取本地存储中的 documentCode
            var documentCode = localStorage.getItem('DocumentCode');
            //alert(documentCode)
            if (documentCode) {
                // 发送请求获取数据
                $.ajax({
                    //url: 'http://localhost:5234/api/Sales/GetDeliveAllById',
                    url: "@ViewBag.BaseUrl/T7/Sales/GetDeliveAllById",
                    type: 'GET',
                    data: { documentCode: documentCode },
                    success: function (res) {
                        if (res.code === 0) {
                            var data = res.data;
                            console.log(data);
                            // 反填表单数据
                            $('#documentCode').val(data[0].documentCode);
                            $('#businessTypeId').val(data[0].businessTypeId);
                            $('#warehouseId').val(data[0].warehouseId);
                            $('#consignee').val(data[0].consignee);
                            $('#freightCost').val(data[0].freightCost);
                            $('#documentDate').val(formatDate(data[0].documentDate));
                            $('#operator').val(data[0].operator);
                            $('#customerName').val(data[0].customerName);
                            $('#phone').val(data[0].phone);
                            $('#handlingFee').val(data[0].handlingFee);
                            $('#documentStatus').val(data[0].documentStatus);
                            $('#auditor').val(data[0].auditor);
                            $('#warehouseId').val(data[0].warehouseId);
                            $('#address').val(data[0].address);
                            $('#businessStatusId').val(data[0].businessStatusId);
                            $('#auditDate').val(formatDate(data[0].auditDate));
                            $('#deliveryDate').val(formatDate(data[0].deliveryDate));
                            $('#remark').val(data[0].remark);

                            // 反填物料表格数据
                            if (data && data.length > 0) {
                                // 假设数组中只有一个元素，取第一个元素
                                const material = data[0];
                                $('#materialTable tbody').empty();
                                var rowCount = 1;
                                var rowHtml = `
                        <tr data-index="0">
                            <td>${rowCount}</td>
                            <td>
                                <input type="text" class="layui-input materialsCode"
                                value="${material.saleCode}" id="materialsCode"
                                placeholder="销售订单号" readonly>
                            </td>
                            <td>
                                <input type="text" class="layui-input materialsCode"
                                    value="${material.materialsCode}" id="materialsCode"
                                    placeholder="物料编码" readonly>
                            </td>
                            <td>
                                <input type="text" class="layui-input materialsName"
                                    value="${material.materialsName}" id="materialsName"
                                    placeholder="物料名称" readonly>
                            </td>
                            <td>
                                <input type="text" class="layui-input"
                                    value="${material.modelSpecification}" id="color"
                                    placeholder="型号规格">
                            </td>
                            <td>
                                <select class="layui-select calulate" id="calulate">
                                    <option value="台" ${material.calulate === '台' ? 'selected' : ''}>台</option>
                                    <option value="箱" ${material.calulate === '箱' ? 'selected' : ''}>箱</option>
                                </select>
                            </td>
                            <td>
                                <input type="number" class="layui-input calulateNumber"
                                    value="${material.calulateNumber}" id="calulateNumber"
                                    placeholder="数量">
                            </td>
                            <td>
                                <input type="number" class="layui-input outBoundNumber"
                                    value="${material.outBoundNumber}" id="outBoundNumber"
                                    placeholder="件数">
                            </td>
                            <td>
                                <input type="text" class="layui-input packRequir"
                                    value="${material.packRequir}" id="packRequir"
                                    placeholder="备注">
                            </td>
                            <td>
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteMaterialButton">删除</button>
                            </td>
                        </tr>`;
                                $('#materialTable tbody').append(rowHtml);
                            }
                            form.render();
                            console.log('表单渲染完成');
                        } else {
                            layer.msg('获取数据失败：' + res.msg, { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.msg('网络请求失败，请检查网络！' + JSON.stringify(xhr), { icon: 2 });
                        console.error(error);
                    }
                });
            } else {
                layer.msg('未获取到单据编码，请检查操作流程', { icon: 2 });
            }

            // 初始化一个空行
            function initEmptyRow() {
                return {
                    saleCode: '',
                    materialsCode: '',
                    materialsName: '物料1',
                    modelSpecification: '',
                    calulate: '箱',
                    calulateNumber: 0,
                    outBoundNumber: 0,
                    packRequir: '',
                };
            }

            // 添加物料行
            function addMaterialRow(material) {
                material = material || initEmptyRow();
                var rowCount = $('#materialTable tbody tr').length + 1;

                var rowHtml =
                    `<tr data-index="${rowCount - 1}">
                                                        <td>${rowCount}</td>
                                                        <td><input type="text" class="layui-input materialsCode" value="${material.materialsCode}" id="materialsCode" placeholder="销售订单号" readonly></td>
                                                        <td><input type="text" class="layui-input materialsCode" value="${material.materialsCode}" id="materialsCode" placeholder="物料编码" readonly><button type="button" class="layui-btn layui-btn-xs selectMaterialButton">选择</button></td>
                                <td><input type="text" class="layui-input materialsName" value="${material.materialsName}" id="materialsName" placeholder="物料名称" readonly></td>
                                                                        <td><input type="text" class="layui-input modelSpecification" value="${material.modelSpecification}" id="modelSpecification" placeholder="型号规格"></td>
                                                        <td><select class="layui-select calulate" id="calulate"><option value="台" ${material.calulate === '台' ? 'selected' : ''}>台</option><option value="箱" ${material.calulate === '箱' ? 'selected' : ''}>箱</option></select></td>
                                                        <td><input type="number" class="layui-input calulateNumber" id="calulateNumber" value="${material.calulateNumber}" placeholder="数量"></td>
                                                        <td><input type="number" class="layui-input outBoundNumber" id="outBoundNumber" value="${material.outBoundNumber}" placeholder="件数"></td>
                                                        <td><input type="text" class="layui-input packRequir" id="packRequir" value="${material.packRequir}" placeholder="备注"></td>
                                                        <td><button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteMaterialButton">删除</button></td>
                                                    </tr>`;

                $('#materialTable tbody').append(rowHtml);
                form.render();
            }

            // 初始化一个空行
            addMaterialRow();

            // 新增物料按钮点击事件
            $('#addMaterialButton').click(function () {
                addMaterialRow();
            });

            // 删除物料按钮点击事件
            $(document).on('click', '.deleteMaterialButton', function () {
                var $tr = $(this).closest('tr');
                layer.confirm('确定删除该物料吗？', function (index) {
                    $tr.remove();
                    // 重新编号
                    $('#materialTable tbody tr').each(function (index) {
                        $(this).find('td:first').text(index + 1);
                    });
                    layer.msg('物料已删除', { icon: 1 });
                });
            });

            // 保存按钮点击事件
            $('#saveButton').click(function () {
                var formData = {
                    documentCode: $('#documentCode').val(),
                    businessTypeId: $('#businessTypeId').val(),
                    warehouseId: $('#warehouseId').val(),
                    documentDate: $('#documentDate').val(),
                    consignee: $('#consignee').val(),
                    operator: $('#operator').val(),
                    customerName: $('#customerName').val(),
                    phone: $('#phone').val(),
                    handlingFee: $('#handlingFee').val(),
                    documentStatus: $('#documentStatus').val(),
                    auditor: $('#auditor').val(),
                    address: $('#address').val(),
                    businessStatusId: $('#businessStatusId').val(),
                    deliveryDate: $('#deliveryDate').val(),
                    freightCost: $('#freightCost').val(),
                    remark: $('#remark').val(),
                    orderMaterials: []
                };

                $('#materialTable tbody tr').each(function () {
                    var $tr = $(this);
                    var calulateNumber = parseFloat($tr.find('#calulateNumber').val());
                    var outBoundNumber = parseFloat($tr.find('#outBoundNumber').val());

                    if (isNaN(calulateNumber)) {
                        calulateNumber = 0;
                    }
                    if (isNaN(outBoundNumber)) {
                        outBoundNumber = 0;
                    }

                    formData.orderMaterials.push({
                        saleCode: $tr.find('.materialsCode').eq(0).val(),
                        materialsCode: $tr.find('.materialsCode').eq(1).val(),
                        materialsName: $tr.find('.materialsName').val(),
                        modelSpecification: $tr.find('#modelSpecification').val(),
                        calulate: $tr.find('#calulate').val(),
                        calulateNumber: calulateNumber,
                        outBoundNumber: outBoundNumber,
                        packRequir: $tr.find('#packRequir').val()
                    });
                });

                if (formData.orderMaterials.length === 0) {
                    layer.msg('请至少添加一个物料', { icon: 2 });
                    return;
                }

                var loadIndex = layer.load(2);
                console.log("查看添加参数", formData);
                $.ajax({
                    //url: 'http://localhost:5090/api/Sales/UpdateDeliveys',
                    url: "@ViewBag.BaseUrl/T8/Sales/UpdateDeliveys",
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 206) {
                            layer.msg(res.msg, { icon: 7 }, function () {
                                if (res.data && res.data.documentCode) {
                                    $('#documentCode').val(res.data.documentCode);
                                }
                                location.href = "/Sales/GetDelivey";
                            });
                        } else {
                            layer.msg(res.msg || '保存失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            });

            // 生成GUID
            function generateUUID() {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0,
                        v = c === 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }

            // 格式化日期
            function formatDate(date) {
                if (date) {
                    var d = new Date(date);
                    var year = d.getFullYear();
                    var month = String(d.getMonth() + 1).padStart(2, '0');
                    var day = String(d.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                }
                return '';
            }
        });
    </script>
</body>
</html>